import cv2
import os
import numpy as np
import argparse

def mark_image(image_path, margin, shape, scale):
    # Read the image
    image = cv2.imread(image_path)
    if image is None:
        raise ValueError("Could not read the image from the given path")
    image = cv2.resize(image, (int(image.shape[1]*scale), int(image.shape[0]*scale)))
    # Calculate the dimensions of the image
    height, width, _ = image.shape

    # Calculate the margin size
    margin_x = int(width * margin)
    margin_y = int(height * margin)

    # Calculate the dimensions of the marked area
    marked_area_width = width - 2 * margin_x
    marked_area_height = height - 2 * margin_y

    # Calculate the number of marks per row and column
    marks_per_row = shape[1]
    marks_per_col = shape[0]

    # Calculate the spacing between marks
    mark_spacing_x = marked_area_width / (marks_per_row - 1)
    mark_spacing_y = marked_area_height / (marks_per_col - 1)

    # Draw the horizontal lines
    for i in range(marks_per_col):
        y = margin_y + i * mark_spacing_y
        cv2.line(image, (int(margin_x), int(y)), (int(width - margin_x), int(y)), (244, 208, 63), 1)

    # Draw the vertical lines
    for j in range(marks_per_row):
        x = margin_x + j * mark_spacing_x
        cv2.line(image, (int(x), int(margin_y)), (int(x), int(height - margin_y)), (244, 208, 63), 1)


    # Save or display the marked image
    cv2.imshow(image_path, image)
    

def main():
    parser = argparse.ArgumentParser(description='Mark an image with * symbols.')
    parser.add_argument('-i','--image_paths', type=str, nargs="+", help='Path to the input image')
    parser.add_argument('-m','--margin', type=float, default=0.1, help='Margin ratio from the edges')
    parser.add_argument('-p','--shape', type=int, nargs=2, default=[3,3], help='Number of * marks in each dimension (rows, cols)')
    parser.add_argument('-s','--scale', type=float, default=1.0, help='Scale of show image')
    args = parser.parse_args()
    if args.image_paths is None:
        parser.print_help()
    else:
        for path in args.image_paths:
            mark_image(path, args.margin, args.shape, args.scale)
        cv2.waitKey(-1)
        cv2.destroyAllWindows()

if __name__ == '__main__':
    main()
    